const App = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLogin: false,
    teamId:0, // 服务队ID（判断是否入会)
    searchInput:"",
    list:[],
    page:1,// 当前页码
    last_page:1,
    scrollHeight: null,
    no_more: false,  // 没有更多数据
    isLoading: true, // 是否正在加载中
    cateindex:0,
    cate_id:0,       // 分类ID（导航）
    cateid:0,  //分类id（表单里使用）
    cate_name:'',
    // 导航菜单
    menuList:[],
    showStatus:0,//弹窗状态
    showTitle:'',//弹窗标题
    showType:0,//弹窗类型，1添加分类，2编辑分类，3添加人员，4编辑人员
    editItem:{},
    maoHao:'',
    fileList: [],
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    that.setData({
      isLogin: App.checkIsLogin(),
      page:1,// 当前页码
      last_page:1,
      no_more: false,  // 没有更多数据
      isLoading: true, // 是否正在加载中
    });
    if (that.data.isLogin) {
      //获取服务队
      that.setData({
        teamId: App.checkTeam()
      });
      // 设置文章列表高度
      that.setListHeight();
      //tab分类
      that.getCate();
      //that.getDataList();
    }
  },
  //活动tab分类
  getCate(){
    console.log("获取分类")
    let that = this;
    App._get('leader', {}, result => {
      that.setData({
        menuList: result.data.categoryList,
        // cate_id:result.data.categoryList[0].category_id
      }); 
      //获取数据
    that.getDataList();
    });
    
  },
  //获取数据列表
  getDataList(isPage, page){
    let obj ={
      page: page || 1,
      searchInput:this.data.searchInput,
      category_id:this.data.cate_id
    };
    let _this = this;
    App._get('leader/lists',obj , function(result) {
      let resList = result.data.list,
      dataList = _this.data.list;
      if (isPage == true) {
        _this.setData({
          list: dataList.concat(resList.data),
          isLoading: false,
          last_page: resList.last_page,
        });
      } else {
        _this.setData({
          list: resList.data,
          isLoading: false,
          last_page: resList.last_page,
        });
      }
    });
  },

  // 搜索查询
  onChangeSearch(e){
    let that = this;
    that.setData({
      searchInput: e.detail.value.searchInput,
      no_more: false,   // 没有更多数据
      isLoading: true,  // 是否正在加载中
      page: 1,          // 当前页码
      last_page:1,      // 最后页码
    }); 
    that.getDataList();
  },
  toSearch(e){
    let that = this;
    that.setData({
      searchInput: e.detail.value,
      no_more: false, // 没有更多数据
      isLoading: true, // 是否正在加载中
      page: 1,          // 当前页码
      last_page:1,       //最后页码
    }); 
    that.getDataList();
  },

  // 详情页跳转
  newsDetail(e){
    let imageUrl = e.currentTarget.dataset.id;
    wx.previewImage({
      current: imageUrl, // 当前显示图片的http链接
      urls: [imageUrl] // 需要预览的图片http链接列表
    })
    // let nid = e.currentTarget.dataset.id;
    // wx.navigateTo({
    //   url: './detail/index?nid=' + nid,
    // })
  },
  /**
   * 下拉到底加载数据
   */
  bindDownLoad() {
    console.log("page",this.data.page)
    console.log("last_page",this.data.last_page)
    // 已经是最后一页
    if (this.data.page >= this.data.last_page) {
      this.setData({
        no_more: true
      });
      return false;
    }
    // 加载下一页列表
    this.getDataList(true, ++this.data.page);
  },

  /**
   * 设置文章列表高度
   */
  setListHeight() {
    let systemInfo = wx.getSystemInfoSync(),
      rpx = systemInfo.windowWidth / 750, // 计算rpx
      tapHeight = Math.floor(rpx * 228), // tap高度
      scrollHeight = systemInfo.windowHeight - tapHeight; // swiper高度
    console.log(
      "高度 =",systemInfo.windowHeight
    );
    this.setData({
      scrollHeight
    });
  },
   // 导航切换
   onChangeNews(e){
    let that = this;
    that.setData({
      cate_id: e.currentTarget.dataset.id,
      list: [],
      page: 1,
      last_page:1,
      no_more: false,
      isLoading: true,
    }); 
    that.getDataList();
  },
  //弹框
  ckButn(e){
    let that = this;
    let data = e.currentTarget.dataset.id
    let type = e.currentTarget.dataset.type
    let showTitle =''
    switch (type){
        case '1':
          showTitle="添加领导团队分类"
          break;
        case '2':
          showTitle="编辑领导团队分类"
          break;
        case '3':
          that.setData({
            fileList:[],
            cate_name:that.data.menuList[0].name,
            cateid:that.data.menuList[0].category_id,
          })
          showTitle="添加领导"
          break;
        case '4':
          let arry = that.data.menuList
          arry.forEach(function(item){  
              if(data.category_id == item.category_id){
                that.setData({
                  cate_name : item.name,
                  cateid:data.category_id
                })
              }
          })
          console.log(data)
          const fileList = [];
          // // 将图片信息添加到fileList数字中
          fileList.push({
            file_id:data.logo.file_id,
            url:data.logo.file_path
          });
          that.setData({fileList})
          showTitle="编辑领导"
          break;
        default:
    }
    that.setData({
      showStatus: true,
      showType:type,
      showTitle,
      editItem:data
     }); 
  },
  //关闭弹窗
  closeBh(){
    let that = this;
    that.setData({
      showStatus: false,
    }); 
  },
  //选择分类
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      cateindex: e.detail.value,
      cateid:this.data.menuList[e.detail.value].category_id,
      cate_name:this.data.menuList[e.detail.value].name,
    })
  },
  // 提交
  submitBtn(e){
    var formData = e.detail.value;//获取表单数据
    let url = ''; //接口地址
    let obj ={};  //提交数据
    //添加分类
    if(this.data.showType ==1){
      url = 'leader/addCate';
      if(formData.cate_name == ""){
        App.showError("标题不能空!");
        return;
      }
      obj.cate_name = formData.cate_name;
      obj.cate_sort = formData.cate_sort;
    }
    // 修改分类
    if(this.data.showType ==2){
      url = 'leader/editCate';
      if(formData.cate_name == ""){
        App.showError("标题不能空!");
        return;
      }
      obj.cate_name = formData.cate_name;
      obj.cate_sort = formData.cate_sort;
      obj.category_id = this.data.editItem.category_id;
    }
    // 添加人员
    if(this.data.showType ==3 || this.data.showType ==4){
      url = 'leader/add';
      if(formData.name == ""){
        App.showError("姓名不能空!");
        return;
      }
      if(formData.company == ""){
        App.showError("部门/地区不能空!");
        return;
      }
      if(formData.duties == ""){
        App.showError("任职时间不能空!");
        return;
      }
      if(formData.position == ""){
        App.showError("职位不能空!");
        return;
      }
      if(formData.sort == ""){
        App.showError("排序不能空!");
        return;
      }
      if(!this.data.fileList.length){
        App.showError("头像照片不能空!");
        return;
      }
      if(this.data.showType ==4){
        url = 'leader/edit';
        obj.id = this.data.editItem.id;
      }
      obj.name = formData.name;
      obj.company = formData.company;
      obj.duties = formData.duties;
      obj.position = formData.position;
      obj.category_id = this.data.cateid;
      obj.sort = formData.sort;
      obj.logo_image_id =this.data.fileList[0].file_id //图片ID
    }
    let that = this;
    App._post_form(url, obj, result => {
      that.closeBh();
      //成功提示
      App.showSuccess(result.msg, function() {
        if(that.data.showType == 1 || that.data.showType == 2){
          that.getCate();
        }
        if(that.data.showType == 3 || that.data.showType == 4){
          that.getDataList();
        }
      });
    });
  },
  // 删除照片
  deleteClick(event) {
    var imgData = this.data.fileList;
    // 通过splice方法删除图片
    imgData.splice(event.detail.index, 1);
    // 更新图片数组
    this.setData({
        fileList: imgData
    })
    console.log(this.data.fileList)
  },
  // 图片上传
  afterRead(event) {
    let that = this;
    // loading加载
    wx.showLoading({title: '上传中...'});
    //获取图片详细信息
    const {file} = event.detail;
    //调用上传图片方法
    that.uploadCompressImg(file).then(res=>{
      App.uploadFile(res,{},function(result){
        const fileList = [];
        // // 将图片信息添加到fileList数字中
        fileList.push({
            url: result.data.file_path,
            file_id:result.data.file_id,
        });
        // 更新存放图片的数组
        that.setData({
            fileList
        });
         wx.hideLoading();//停止loading
      })
    })

  },
  //图片压缩
  uploadCompressImg(file) {
    let that = this
    return new Promise(function(resolve, reject){
      let file_url = file.tempFilePath
      console.log(file);
      if(file.size < 500*1024){
        console.log("size",file.size)
        console.log("file_url",file_url)
        resolve(file_url);
      }else{
          // 获得原始图片大小
          wx.getImageInfo({
            src: file_url,
            success(res) {
              console.log(res);
            
              let originHeight = res.height;
              let originWidth = res.width;
              // 压缩比例
              // 最大尺寸限制
              let maxWidth = 1024,
                maxHeight = 1024;
              // 目标尺寸
              let targetWidth = originWidth,
                targetHeight = originHeight;
              // 等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              // 更新 canvas 大小
              that.setData({
                "cw": targetWidth,
                "ch": targetHeight
              });
              // 尝试压缩文件，创建 canvas
              let ctx = wx.createCanvasContext('canvas');
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              //通过得到图片旋转的角度来调整显示方向以正确显示图片，主要解决 ios 系统上的图片会有旋转的问题
              let orientation = res.orientation;
              if (orientation == 'right') { //exif的6
                that.setData({
                  "cw": targetHeight,
                  "ch": targetWidth
                });
                ctx.rotate(90 * Math.PI / 180);
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight, 0, -targetHeight, that.data.ch, that.data.cw);
              } else {
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight);
              }

              ctx.draw(false, function () {
                // 获得新图片输出
                wx.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  canvasId: 'canvas',
                  destWidth: targetWidth,
                  destHeight: targetHeight,
                  quality: 0.9,
                  fileType: "jpg",
                  success: (res) => {
                    console.log(res)
                    resolve(res.tempFilePath);
                  },
                  fail: (err) => {
                    console.error(err)
                  }
                }, this)
              })
            }
          })
      }
    })
  },

})